/**
 * 
 */
package freedom.needle.tps;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freedom.needle.dao.TpsInfoDao;
import freedom.needle.entity.TpsInfo;

/**
 * @author charlie
 *
 */
public class TpsWindowDeamon implements Runnable{
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	private long interval = 60000;//刷新时间间隔
	private TpsWindow[] tpsWindows;
	private TpsInfoDao tpsInfoDao;

	/**
	 * @param interval
	 * @param sleepWindow
	 */
	public TpsWindowDeamon(long interval, TpsWindow[] tpsWindows) {
		super();
		this.interval = interval;
		this.tpsWindows = tpsWindows;
	}

	@Override
	public void run() {
		while (true) {
			try {
				saveTpsSnapshoot();
				Thread.sleep(interval);
			} catch (InterruptedException e) {
				logger.warn("sleep is interrupted!");
			} catch(Exception e) {
				logger.error("saveTpsSnapshoot error!", e);
			}
		}
	}
	
	private void saveTpsSnapshoot() {
		for (int i = 0; i < tpsWindows.length; i++) {
			if(tpsWindows[i].isOpen()) {
				TpsInfo tpsInfo = tpsWindows[i].snapshoot();
				//save tps
				tpsInfoDao.save(tpsInfo);
				
			}
		}
	}

	/**
	 * @param tpsInfoDao the tpsInfoDao to set
	 */
	public void setTpsInfoDao(TpsInfoDao tpsInfoDao) {
		this.tpsInfoDao = tpsInfoDao;
	}

}
